﻿// iBurn.cpp : 定义应用程序的入口点。
//

#include "stdafx.h"
#include "iBurn.h"
#include "usbfind.h"
#include <shellapi.h>
#include <string>
#include "ISOFormat.h"

#define MAX_LOADSTRING 100
#define WND_W 720
#define WND_H  450
// 全局变量:
HINSTANCE hInst;								// 当前实例
TCHAR szTitle[MAX_LOADSTRING];					// 标题栏文本
TCHAR szWindowClass[MAX_LOADSTRING];			// 主窗口类名
TCHAR szUseInfo[512];

TCHAR Imagename[260]={L"\0"};
ITaskbarList3 *g_TaskList = NULL;

// 此代码模块中包含的函数的前向声明:
ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK	About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPTSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

 	// TODO: 在此放置代码。
	MSG msg;
	HACCEL hAccelTable;

	// 初始化全局字符串
	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_IBURN, szWindowClass, MAX_LOADSTRING);
	LoadString(hInstance,IDS_APP_USEINFO,szUseInfo,512);
	MyRegisterClass(hInstance);

	// 执行应用程序初始化:
	if (!InitInstance (hInstance, nCmdShow))
	{
		return FALSE;
	}

	hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_IBURN));

	// 主消息循环:
	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	return (int) msg.wParam;
}



//
//  函数: MyRegisterClass()
//
//  目的: 注册窗口类。
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);
	
	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_IBURN));
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= NULL/*MAKEINTRESOURCE(IDC_IBURN)*/;
	wcex.lpszClassName	= szWindowClass;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

	return RegisterClassEx(&wcex);
}

//
//   函数: InitInstance(HINSTANCE, int)
//
//   目的: 保存实例句柄并创建主窗口
//
//   注释:
//
//        在此函数中，我们在全局变量中保存实例句柄并
//        创建和显示主程序窗口。
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;

   hInst = hInstance; // 将实例句柄存储在全局变量中
   DWORD wndStyle=WS_OVERLAPPEDWINDOW&~WS_MAXIMIZEBOX&~WS_SIZEBOX;
   RECT rect={0,0,WND_W,WND_H};
   AdjustWindowRectEx(&rect,wndStyle,FALSE,NULL);
   //hWnd = CreateWindowEx(WS_EX_ACCEPTFILES,szWindowClass, szTitle, WS_OVERLAPPEDWINDOW&~WS_MAXIMIZEBOX&~WS_SIZEBOX,
	  // (GetSystemMetrics(SM_CXSCREEN)-WND_W)/2, (GetSystemMetrics(SM_CYSCREEN)-WND_H)/2, (rect.right-rect.left),(rect.bottom-rect.top), NULL, NULL, hInstance, NULL);
   hWnd = CreateWindowEx(WS_EX_ACCEPTFILES,szWindowClass, szTitle, WS_OVERLAPPEDWINDOW&~WS_MAXIMIZEBOX&~WS_SIZEBOX,
	   (GetSystemMetrics(SM_CXSCREEN)-WND_W)/2, (GetSystemMetrics(SM_CYSCREEN)-WND_H)/2, WND_W,WND_H, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);
   
   HRESULT hr;
   hr = CoCreateInstance(CLSID_TaskbarList,NULL,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&g_TaskList));
   	if (!SUCCEEDED(hr))
	{
		return FALSE;
	}

   return TRUE;
}

//
//  函数: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  目的: 处理主窗口的消息。
//
//  WM_COMMAND	- 处理应用程序菜单
//  WM_PAINT	- 绘制主窗口
//  WM_DESTROY	- 发送退出消息并返回
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	HWND hCob;
	HWND hSize/*,hStaticI,hStaticF,hStaticT*/;
	HWND hSt1,hSt2,hSt3,hSt4,hSt5;
	HWND hEdit;
	HWND hBt1,hBt2,hBt3;
	HWND hPd;
	PAINTSTRUCT ps;
	HDC hdc;

	

	HFONT hFont=(HFONT)GetStockObject(DEFAULT_GUI_FONT);
	LOGFONT logFont={0};
	GetObject(hFont,sizeof(logFont),&logFont);
	DeleteObject(hFont);
	hFont=NULL;
	OSVERSIONINFO osvi;
	BOOL bIsWindows8orLater;

	ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
	GetVersionEx(&osvi);
	bIsWindows8orLater =
		((osvi.dwMajorVersion > 6) ||
		((osvi.dwMajorVersion == 6) && (osvi.dwMinorVersion >= 2)));
	if (!bIsWindows8orLater)
	{
		logFont.lfHeight = 15;
		logFont.lfWeight = FW_NORMAL;
		wcscpy_s(logFont.lfFaceName, L"MS Shell Dlg");
	}
	else{
		logFont.lfHeight = 18;
		logFont.lfWeight = FW_NORMAL;
		wcscpy_s(logFont.lfFaceName, L"Microsoft Yahei UI");
	}
	hFont = CreateFontIndirect(&logFont);
	//SelectObject(hdc,hFont);

	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// 分析菜单选择:
		switch (wmId)
		{
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		case IDC_BUTTON_VIEW:
			//MessageBox(NULL,L"World",L"Hello",MB_OK);
			{
				if(OpenImageFile(hWnd,Imagename)==0)
				{
					TCHAR SizeStr[120]={L"\0"};
					MessageBox(hWnd,Imagename,L"选取的镜像文件是:",MB_OK|MB_ICONASTERISK);
					SetWindowText(GetDlgItem(hWnd,IDC_EDIT_IMAGE),Imagename);
					HANDLE hFile;
					LARGE_INTEGER FileSize;
					hFile=CreateFile(Imagename,GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
					if(hFile !=INVALID_HANDLE_VALUE)
					{
						//UINT64 dsize=0;
						GetFileSizeEx(hFile,&FileSize);
					    //long long SizeMB=((dwFileSize.QuadPart/1024)/1024+1);
						swprintf_s(SizeStr,L"%lld Bytes ||%4.1f KB ||%4.2f MB ||%4.2f GB\n", FileSize.QuadPart, (float)FileSize.QuadPart/1024, (float)FileSize.QuadPart/(1024*1024), (float)FileSize.QuadPart/(1024*1024*1024));
						//wsprintf(SizeStr,L"%d",dsize);
						//wcscat_s(SizeStr,L" 字节");
						SetWindowText(GetDlgItem(hWnd,IDC_STATIC_SIZE),SizeStr);
					}
					CloseHandle(hFile);
				}
				else
				{
					wcscpy_s(Imagename,L"\0");
					//if(wcscmp(Imagename,L"\0")==0)
						//MessageBox(hWnd,L"Image",L"No Select",MB_OK);
				}
			}
			break;
		case IDC_BUTTON_BOOTFIX:
			{
				
				//MessageBox(hWnd,L"IDC_BUTTON_BOOTFIX",L"修复U盘启动扇区",MB_OK);
				SendMessage(GetDlgItem(hWnd,IDC_PROCESS_TIME),PBM_SETSTATE, (WPARAM)PBST_NORMAL,0);
				g_TaskList->SetProgressState(hWnd, TBPF_NORMAL);
		       // g_TaskList->SetProgressValue(hWnd, (ULONG)50, (ULONG)100);
				
				LRESULT i=SendMessage(GetDlgItem(hWnd,IDC_COMBOX_DEVICE),CB_GETCURSEL,0,0L);
				if(i==-1)
					MessageBox(hWnd,L"请选取有效的设备！",L"没有可移动磁盘",MB_OK|MB_ICONWARNING);
				//g_TaskList->SetProgressValue(hWnd, (ULONG)100, (ULONG)100);
				if(i>=0&&i<=26)
				{
					SendMessage(GetDlgItem(hWnd,IDC_PROCESS_TIME),PBM_SETPOS, (WPARAM)50, 0);
					g_TaskList->SetProgressValue(hWnd, (ULONG)50, (ULONG)100);
					//MessageBox(hWnd,DefUsbDevice[i].driveLetter,L"Hello",MB_OK);
					if(UsbBootFix(hWnd,DefUsbDevice[i].deviceLetter)!=true)
					{
						MessageBox(hWnd,L"Can't Fix USB disk Boot",L"Boot Fix Error",MB_OK|MB_ICONHAND);
						SendMessage(GetDlgItem(hWnd,IDC_PROCESS_TIME), PBM_SETSTATE, (WPARAM)PBST_ERROR, 0);
						g_TaskList->SetProgressState(hWnd, TBPF_ERROR);
						g_TaskList->SetProgressValue(hWnd, (ULONG)50, (ULONG)100);
					}
					else
					{
					SendMessage(GetDlgItem(hWnd,IDC_PROCESS_TIME),PBM_SETPOS, (WPARAM)100, 0);
					g_TaskList->SetProgressValue(hWnd, (ULONG)100, (ULONG)100);
					MessageBoxW(hWnd,L"Fix USB Boot Success!",L"Fix USB Boot",MB_OK|MB_ICONINFORMATION);
					}
				}
				//FindUSBDisk();
			}
			break;
		case IDC_BUTTON_MAKE:
			{
					//wcscpy_s(Imagename,L"\0");
					if(wcscmp(Imagename,L"\0")==0)
						MessageBox(hWnd,L"请选择有效镜像",L"没有镜像",MB_OK|MB_ICONWARNING);
					else
					{
						LRESULT i=SendMessage(GetDlgItem(hWnd,IDC_COMBOX_DEVICE),CB_GETCURSEL,0,0L);
						if(i==-1)
							MessageBox(hWnd,L"请选取有效的设备！",L"没有可移动磁盘",MB_OK|MB_ICONWARNING);
		                if(i>=0&&i<26)
						{
							SendMessage(GetDlgItem(hWnd,IDC_PROCESS_TIME),PBM_SETSTATE, (WPARAM)PBST_NORMAL,0);
							g_TaskList->SetProgressState(hWnd, TBPF_NORMAL);

							FormatDrive(hWnd,DefUsbDevice[i].deviceLetter);
							SendMessage(GetDlgItem(hWnd,IDC_PROCESS_TIME),PBM_SETPOS, (WPARAM)10, 0);
							g_TaskList->SetProgressValue(hWnd, (ULONG)10, (ULONG)100);

							if(ExtractToUsbDisk(hWnd,Imagename,DefUsbDevice[i].RootPath)==-1)
							{
								g_TaskList->SetProgressState(hWnd, TBPF_ERROR);
								g_TaskList->SetProgressValue(hWnd, (ULONG)50, (ULONG)100);
							}
							SendMessage(GetDlgItem(hWnd,IDC_PROCESS_TIME),PBM_SETPOS, (WPARAM)90, 0);
							g_TaskList->SetProgressValue(hWnd, (ULONG)90, (ULONG)100);

						    if(UsbBootFix(hWnd,DefUsbDevice[i].deviceLetter)!=true)
							{
								MessageBox(hWnd,L"Can't Fix USB disk Boot",L"Boot Fix Error",MB_OK|MB_ICONHAND);
								SendMessage(GetDlgItem(hWnd,IDC_PROCESS_TIME), PBM_SETSTATE, (WPARAM)PBST_ERROR, 0);
								g_TaskList->SetProgressState(hWnd, TBPF_ERROR);
								g_TaskList->SetProgressValue(hWnd, (ULONG)90, (ULONG)100);
							}
							else
							{
							SendMessage(GetDlgItem(hWnd,IDC_PROCESS_TIME),PBM_SETPOS, (WPARAM)100, 0);
							g_TaskList->SetProgressValue(hWnd, (ULONG)100, (ULONG)100);
							MessageBoxW(hWnd,L"Fix USB Boot Success!",L"Fix USB Boot",MB_OK|MB_ICONINFORMATION);
							}
							//WriteImageToUsbDisk
						}
						//MessageBox(hWnd,Imagename,L"Select Image",MB_OK);

					}
			}
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
		case WM_CREATE:
			{
			SetWindowLongPtr( hWnd, GWL_EXSTYLE, GetWindowLongPtr(hWnd, GWL_EXSTYLE) | WS_EX_LAYERED);
			SetLayeredWindowAttributes(hWnd,0,250,LWA_ALPHA/*LWA_COLORKEY*/);
            ChangeWindowMessageFilter(WM_DROPFILES, MSGFLT_ADD);
            ChangeWindowMessageFilter(WM_COPYDATA, MSGFLT_ADD);
            ChangeWindowMessageFilter(0x0049,MSGFLT_ADD);
			//FindUSBDisk();
			InitCommonControls();

			DWORD dwCobExStyle=WS_EX_LEFT|WS_EX_LTRREADING|WS_EX_RIGHTSCROLLBAR|WS_EX_NOPARENTNOTIFY;
			DWORD dwCobStyle= WS_CHILDWINDOW|WS_VISIBLE|WS_TABSTOP|CBS_DROPDOWNLIST|CBS_SORT|CBS_HASSTRINGS;

			DWORD dwEditExSt=WS_EX_LEFT|WS_EX_LTRREADING|WS_EX_RIGHTSCROLLBAR|WS_EX_NOPARENTNOTIFY|WS_EX_CLIENTEDGE;
			DWORD dwEditSt=WS_CHILDWINDOW|WS_VISIBLE|WS_TABSTOP|ES_LEFT|ES_AUTOHSCROLL;

			DWORD dwSizeExSt=WS_EX_LEFT|WS_EX_LTRREADING|WS_EX_RIGHTSCROLLBAR|WS_EX_TRANSPARENT|WS_EX_NOPARENTNOTIFY;
			DWORD dwSizeSt=WS_CHILDWINDOW|WS_VISIBLE|WS_GROUP|SS_LEFT;

			DWORD dwBtExSt=WS_EX_LEFT|WS_EX_LTRREADING|WS_EX_RIGHTSCROLLBAR|WS_EX_NOPARENTNOTIFY;
			DWORD dwBtSt=WS_CHILDWINDOW|WS_VISIBLE|WS_TABSTOP|BS_PUSHBUTTON|BS_TEXT;

			DWORD dwpgExSt=WS_EX_LEFT|WS_EX_LTRREADING|WS_EX_RIGHTSCROLLBAR|WS_EX_NOPARENTNOTIFY;
			DWORD dwpgSt=WS_CHILDWINDOW|WS_VISIBLE;

			hCob=CreateWindowEx(dwCobExStyle,WC_COMBOBOX,L"Driver",dwCobStyle,120,40,490,24,hWnd,HMENU(IDC_COMBOX_DEVICE),hInst,NULL);
			hSt1=CreateWindowEx(dwSizeExSt,WC_STATIC,L"选择设备:",dwSizeSt,30,40,80,24,hWnd,NULL,hInst,NULL);
			hSt2=CreateWindowEx(dwSizeExSt,WC_STATIC,L"选择镜像:",dwSizeSt,30,80,80,24,hWnd,NULL,hInst,NULL);
			hEdit=CreateWindowEx(dwEditExSt,WC_EDIT,L"",dwEditSt,120,80,390,24,hWnd,HMENU(IDC_EDIT_IMAGE),hInst,NULL);
			hBt1=CreateWindowEx(dwBtExSt,WC_BUTTON,L"浏览...",dwBtSt,520,80,90,24,hWnd,HMENU(IDC_BUTTON_VIEW),hInst,NULL);
			hSt3=CreateWindowEx(dwSizeExSt,WC_STATIC,L"文件大小:",dwSizeSt,30,120,80,24,hWnd,NULL,hInst,NULL);
			hSize=CreateWindowEx(dwSizeExSt,WC_STATIC,L" 0 字节",dwSizeSt,120,120,490,24,hWnd,HMENU(IDC_STATIC_SIZE),hInst,NULL);
			hSt4=CreateWindowEx(dwSizeExSt,WC_STATIC,szUseInfo,dwSizeSt,120,150,490,72,hWnd,NULL,hInst,NULL);
			
			hSt5=CreateWindowEx(dwSizeExSt,WC_STATIC,L"耗时:",dwSizeSt,30,250,80,24,hWnd,NULL,hInst,NULL);
			hPd=CreateWindowEx(dwpgExSt,PROGRESS_CLASS,L"ProgressTime",dwpgSt,120,250,490,24,hWnd,HMENU(IDC_PROCESS_TIME),hInst,NULL);

			hBt2=CreateWindowEx(dwBtExSt,WC_BUTTON,L"修复U盘启动扇区",dwBtSt,370,345,120,24,hWnd,HMENU(IDC_BUTTON_BOOTFIX),hInst,NULL);
			hBt3=CreateWindowEx(dwBtExSt,WC_BUTTON,L"制作USB启动盘",dwBtSt,510,345,100,24,hWnd,HMENU(IDC_BUTTON_MAKE),hInst,NULL);

			//SendMessage(hCob,CB_SHOWDROPDOWN,TRUE,0);
			SendMessage(hCob,WM_SETFONT,(WPARAM)hFont,lParam);
			SendMessage(hEdit,WM_SETFONT,(WPARAM)hFont,lParam);
			SendMessage(hSt1,WM_SETFONT,(WPARAM)hFont,lParam);
			SendMessage(hSt2,WM_SETFONT,(WPARAM)hFont,lParam);
			SendMessage(hBt1,WM_SETFONT,(WPARAM)hFont,lParam);
			SendMessage(hBt2,WM_SETFONT,(WPARAM)hFont,lParam);
			SendMessage(hBt3,WM_SETFONT,(WPARAM)hFont,lParam);
			SendMessage(hSt3,WM_SETFONT,(WPARAM)hFont,lParam);
			SendMessage(hSt4,WM_SETFONT,(WPARAM)hFont,lParam);
			SendMessage(hSt5,WM_SETFONT,(WPARAM)hFont,lParam);
			SendMessage(hSize,WM_SETFONT,(WPARAM)hFont,lParam);

			if(FindUSBDisk()>0)
			{
				for(uInt i=0;i<FindUSBDisk();i++)
				{
				 SendMessage(hCob,CB_ADDSTRING,0,(LPARAM)(DefUsbDevice[i].Info));
				}
			}
			//SendMessage(hCob,CB_ADDSTRING,0,(LPARAM)(L"ComboBox 测试:"));
			//SendMessage(hCob,CB_SETCURSEL,0,0L);

		}
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		// TODO: 在此添加任意绘图代码...
		EndPaint(hWnd, &ps);
		break;
	case WM_DEVICECHANGE:
		{
			//CB_RESETCONTENT
			SendMessage(GetDlgItem(hWnd,IDC_COMBOX_DEVICE),CB_RESETCONTENT,0,0L);
			//This message is sent by an application to remove all items from the list box and edit control of a combo box.
		     if(FindUSBDisk()>0)
			{
				for(uInt i=0;i<FindUSBDisk();i++)
				{
					SendMessage(GetDlgItem(hWnd,IDC_COMBOX_DEVICE),CB_ADDSTRING,0,(LPARAM)(DefUsbDevice[i].Info));
				}
			}
		}
		break;
    case WM_SHOWWINDOW:
			{
				DragAcceptFiles(hWnd, TRUE);
			}
			break;
	case WM_DROPFILES:
		{
						WCHAR ipath[32678] = {0};
						UINT nFileCnt = DragQueryFile((HDROP) wParam, 0xFFFFFFFF, NULL, 0);
						 if (DragQueryFile((HDROP) wParam, nFileCnt-1, ipath, 32678))
						 {
							 std::wstring wstr = ipath;

							 std::wstring::size_type loc2 = wstr.rfind(L".iso");

							 if (loc2 != wstr.length() - 4)
								break;
							 SetWindowText(GetDlgItem(hWnd, IDC_EDIT_IMAGE), ipath);
						 }
		}break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}

// “关于”框的消息处理程序。
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	UNREFERENCED_PARAMETER(lParam);
	switch (message)
	{
	case WM_INITDIALOG:
		return (INT_PTR)TRUE;

	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
		{
			EndDialog(hDlg, LOWORD(wParam));
			return (INT_PTR)TRUE;
		}
		break;
	}
	return (INT_PTR)FALSE;
}
